import os, json

from appium.options.android import UiAutomator2Options
from selenium import webdriver
import appium.webdriver
import logging.handlers
from config import DIR_PATH, HOST


class GetDriver:
    __app_driver = None
    __web_driver = None

    # 获取App Driver
    @classmethod
    def get_app_driver(cls):
        if cls.__app_driver is None:
            desired_caps = {
                "platformName": "Android",
                "platformVersion": "9",
                # ————————————用模拟器————————————————
                "deviceName": "emulator-5554",  # 2. 确认：雷电模拟器的设备名（adb devices 输出一致）
                "appPackage": "com.tpshop.malls",  # 关键：改回TPShop的包名，杜绝系统设置包名
                "appActivity": ".SPMainActivity",  # 关键：用可导出的入口（若aapt查的是其他名，替换这里）
                "automationName": "UiAutomator2",
                "noReset": True,  # 强制启用：告诉Appium“应用已预装，无需安装”
                "dontStopAppOnReset": True  # 辅助：避免连接时关闭已启动的应用
            }
            # 设置driver
            options = UiAutomator2Options()
            options.load_capabilities(desired_caps)
            cls.__app_driver = appium.webdriver.Remote("http://127.0.0.1:4723", options=options)
            print("当前连接的应用包名：", cls.__app_driver.current_package)
            print("当前连接的应用包名：", cls.__app_driver.current_activity)
            print("连接成功！")
        return cls.__app_driver

    # 获取Web Driver
    @classmethod
    def get_web_driver(cls):
        if cls.__web_driver is None:
            cls.driver = webdriver.Chrome()
            cls.driver.get(HOST)
            cls.driver.maximize_window()
        return cls.driver


# 读取json工具
def read_json(filename, key):
    file_path = DIR_PATH + os.sep + "data" + os.sep + filename
    arrs = []
    with open(file_path, "r", encoding="utf-8")as f:
        for data in json.load(f).get(key):
            arrs.append(tuple(data.values())[1:])
        return arrs

def write_json(value):
    file_path = DIR_PATH + os.sep + "data" + os.sep + "expect.json"
    with open(file_path,"w",encoding="utf-8")as f:
        data = {"expect":[{"desc":"app订单编号","order_no":value}]}
        json.dump(data,f)

# 日志封装
class GetLog:
    __log = None
    @classmethod
    def get_log(cls):
        if cls.__log is None:
            # 获取日志器
            cls.__log = logging.getLogger()
            # 设置入口级别
            cls.__log.setLevel(logging.INFO)
            # 获取处理器
            filename = DIR_PATH + os.sep + "log" + os.sep + "tpshop_auto.log"
            tf = logging.handlers.TimedRotatingFileHandler(filename=filename,
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=3,
                                                           encoding="utf-8")
            # 获取格式器
            fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fm = logging.Formatter(fmt)
            # 将格式器添加到处理器
            tf.setFormatter(fm)
            # 将处理器添加到日志器
            cls.__log.addHandler(tf)
        # 返回日志器
        return cls.__log

if __name__ == '__main__':
    # 预期：[(),()]
    # GetLog.get_log().info("日志测试")
    # write_json("202112312300001")
    # print(read_json("expect.json", "expect")[0][0])
    # GetDriver.get_app_driver()#测试是否连接app
    GetDriver.get_web_driver()#测试是否连接web


